Triplet Sum Close to Target (medium)

Problem Statement #

Given an array of unsorted numbers and a target number, find a triplet in the array whose sum is as close to the target number as possible, return the sum of the triplet. If there are more than one such triplet, return the sum of the triplet with the smallest sum.

Example 1:

Input: [-2, 0, 1, 2], target=2
Output: 1
Explanation: The triplet [-2, 1, 2] has the closest sum to the target.

Example 2:

Input: [-3, -1, 1, 2], target=1
Output: 0
Explanation: The triplet [-3, 1, 2] has the closest sum to the target.

Example 3:

Input: [1, 0, 1, 1], target=100
Output: 3
Explanation: The triplet [1, 1, 1] has the closest sum to the target.

Try it yourself #

Try solving this question here:

0 of 3 Tests Passed
ResultInputExpected OutputActual OutputReason
searchTriplet([-2, 0, 1, 2], 2)1-1Incorrect Output
searchTriplet([-3, -1, 1, 2], 1)0-1Incorrect Output
searchTriplet([1, 0, 1, 1], 100)3-1Incorrect Output
4.705s

Solution #

This problem follows the Two Pointers pattern and is quite similar to Triplet Sum to Zero.

We can follow a similar approach to iterate through the array, taking one number at a time. At every step, we will save the difference between the triplet and the target number, so that in the end, we can return the triplet with the closest sum.

Code #

Here is what our algorithm will look like:

Output

0.507s

1 0 3

Time complexity #

Sorting the array will take O(NlogN)O(N* logN). Overall searchTriplet() will take O(NlogN+N2)O(N * logN + N^2), which is asymptotically equivalent to O(N2)O(N^2).

Space complexity #

The space complexity of the above algorithm will be O(N)O(N) which is required for sorting.

Mark as Completed
←    Back
Triplet Sum to Zero (medium)
Next    →
Triplets with Smaller Sum (medium)